import path from "path";
import fs from "fs";
import MarkdownIt from "markdown-it";

const mdRelationMap = {};
export default function markdownPlugin() {
  return {
    //插件名称
    name: "vite:markdownPlugin",
    //   强制插件排序
    //   pre 在vite核心插件之前调用它
    //   post 在vite构建插件之后调用它
    //   默认 在vite核心插件之后调用它
    enforce: "pre",
    /* 配置热重载 */
    handleHotUpdate(ctx) {
      const { file, server, modules } = ctx;
      if (path.extname(file) !== ".md") return;
      const relationIds = mdRelationMap[path.resolve(file)];
      const relationModules = [];
      relationIds.forEach((relationId) => {
        const relationModule = [
          ...server.moduleGraph.getModulesByFile(relationId),
        ][0];
        server.ws.send({
          type: "update",
          updates: [
            {
              type: "js-update",
              path: relationModule.file,
              acceptedPath: relationModule.file,
              timestamp: new Date().getTime(),
            },
          ],
        });
        relationModules.push(relationModule);
      });
      return [...modules, ...relationModules];
    },
    // 插件功能实现
    transform(code, id, opt) {
      if (id.indexOf(".vue") != -1) {
        let markdownExp = /<g-markdown[^]*?<\/g-markdown>/g;
        let markdownMathList = code.match(markdownExp);
        const filePathExp = /(?<=file=("|')).*(?=('|"))/;
        markdownMathList.forEach((markdown) => {
          let mdPath = markdown.match(filePathExp)[0];
          const markdwonPath = path.resolve(path.dirname(id), mdPath);
          const mdText = fs.readFileSync(markdwonPath, "utf-8");

          const md = new MarkdownIt();
          const htmlText = md.render(mdText);

          code = code.replace(markdown, htmlText);

          if (!mdRelationMap[markdwonPath]) {
            mdRelationMap[markdwonPath] = [];
          }
          mdRelationMap[markdwonPath].push(id);
        });
        return code;
      }
    },
  };
}
